package Thread.New.带返回值的线程创建.线程工具;

import java.util.concurrent.Exchanger;

public class Exchanger_Use {
    //用户线程间交换数据(String)对象exchanger
    static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        //创建2个子线程分别执行
        SubThread1 subThread1 = new SubThread1();
        SubThread2 subThread2 = new SubThread2();
        subThread1.start();
        subThread2.start();
    }

    static class SubThread1 extends Thread {
        @Override
        public void run() {
            try {
                System.out.println(getName() + "开始执行");
                //模拟执行完成后，获取结果result1，并将result1交换给对方线程
                sleep(1000);
                String result1 = "1000";
                System.out.println(getName()+"先执行完毕,进入等待状态\n------------------");
                String result2 = exchanger.exchange(result1);
                System.out.println(getName()+"退出等待状态");
                //这里就是使用exchange方法进入等待了
                //待两个线程都执行完毕后，交换数据进行比较
                System.out.println(getName() + " 线程执行结果为" + result1 + " ,另一个的执行结果为" + result2 +
                        ",结果比较为" + result1.equals(result2));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class SubThread2 extends Thread {
        @Override
        public void run() {
            try {
                System.out.println(getName() + "开始执行");
                //模拟执行完成后，获取结果result2，并将result2交换给对方线程
                sleep(3000);
                String result2 = "2000";
                String result1 = exchanger.exchange(result2);
                //待两个线程都执行完毕后，交换数据进行比较
                System.out.println(getName() + " 线程执行结果为" + result1 + " ,另一个的执行结果为" + result2 +
                        ",结果比较为" + result1.equals(result2));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

